package cn.wangqi.personal.controller;

import cn.wangqi.personal.domain.Address;
import cn.wangqi.personal.domain.BlogArticle;
import cn.wangqi.personal.domain.BlogUser;
import cn.wangqi.personal.service.IBlogArticleService;
import cn.wangqi.personal.service.IBlogUserService;
import cn.wangqi.personal.util.AddressUtil;
import cn.wangqi.personal.util.IPUtil;
import cn.wangqi.personal.util.Page;
import cn.wangqi.personal.util.StringUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * HomeController
 *
 * @author admin
 * @date 2017/9/22.
 */
@Controller
public class HomeController {

    @Resource
    private IBlogArticleService blogArticleService;

    @Resource
    private IBlogUserService blogUserService;

    @RequestMapping("home.html")
    public String index(HttpServletRequest request, String author, ModelMap modelMap) {
        try {
            Subject subject = SecurityUtils.getSubject();
            String userName = null;
            if (subject.isAuthenticated() || subject.isRemembered()) {
                userName = subject.getPrincipal().toString();
                modelMap.put("user", blogUserService.findBlogUserByUserName(userName));
            }
            if (StringUtil.isEmpty(author)) {
                if(StringUtil.isNotEmpty(userName)){
                    author = userName;
                }else{
                    author = "会飞的齐齐";
                }
            }
            BlogUser blogUser = blogUserService.findBlogUserByUserName(author);
            modelMap.put("author", blogUser);
            String ip = IPUtil.getIpAddr(request);
            Address address = AddressUtil.getAddress(ip);
            Page page = new Page();
            page.setStart(0);
            page.setPageSize(10);
            List<BlogArticle> blogArticleList = blogArticleService.listBlogArticle(blogUser.getId(),page);
            List<BlogArticle> recomArticleList = blogArticleService.findRecomArticleByUserId(blogUser.getId());
            modelMap.put("blogArticleList", blogArticleList);
            modelMap.put("recomArticleList", recomArticleList);
            return "home";
        } catch (Exception e) {
            e.printStackTrace();
            return "index";
        }
    }

}
